// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <melon/random.h>
#include <gtest/gtest.h>
#include <pollux/common/exception/exception.h>

using namespace kumo::pollux::dwio::common::exception;
using namespace kumo::pollux;

namespace {
void testTraceCollectionSwitchControl(bool enabled) {
  // Logged exception is system type of pollux exception.
  // Disable rate control in the test.
  FLAGS_pollux_exception_user_stacktrace_rate_limit_ms = 0;
  FLAGS_pollux_exception_system_stacktrace_rate_limit_ms = 0;

  // NOTE: the user flag should not affect the tracing behavior of system type
  // of exception collection.
  FLAGS_pollux_exception_user_stacktrace_enabled = melon::Random::oneIn(2);
  FLAGS_pollux_exception_system_stacktrace_enabled = enabled ? true : false;
  try {
    throw LoggedException("Test error message");
  } catch (PolluxException& e) {
    SCOPED_TRACE(fmt::format(
        "enabled: {}, user flag: {}, sys flag: {}",
        enabled,
        FLAGS_pollux_exception_user_stacktrace_enabled,
        FLAGS_pollux_exception_system_stacktrace_enabled));
    ASSERT_TRUE(e.exceptionType() == PolluxException::Type::kSystem);
    ASSERT_EQ(enabled, e.stackTrace() != nullptr);
  }
}

struct ExceptionCounter {
  int numExceptions = 0;
  int numWarnings = 0;
};

class TestExceptionLogger : public ExceptionLogger {
 public:
  explicit TestExceptionLogger(std::shared_ptr<ExceptionCounter> counter)
      : counter_(std::move(counter)) {}

  void logException(
      const char* /* unused */,
      size_t /* unused */,
      const char* /* unused */,
      const char* /* unused */,
      const char* /* unused */) override {
    ++counter_->numExceptions;
  }

  void logWarning(
      const char* /* unused */,
      size_t /* unused */,
      const char* /* unused */,
      const char* /* unused */,
      const char* /* unused */) override {
    ++counter_->numWarnings;
  }

 private:
  std::shared_ptr<ExceptionCounter> counter_;
};
} // namespace

TEST(LoggedExceptionTest, basic) {
  // Check the exception count.
  // no logger
  ASSERT_ANY_THROW(throw LoggedException("Test error message"));

  auto counter = std::make_shared<ExceptionCounter>();
  registerExceptionLogger(std::make_unique<TestExceptionLogger>(counter));

  ASSERT_ANY_THROW(throw LoggedException("Test error message"));
  ASSERT_EQ(1, counter->numExceptions);
  ASSERT_EQ(0, counter->numWarnings);

  DWIO_WARN("test warning");
  ASSERT_EQ(1, counter->numExceptions);
  ASSERT_EQ(1, counter->numWarnings);

  ASSERT_ANY_THROW(throw LoggedException("Test error message #2"));
  ASSERT_EQ(2, counter->numExceptions);
  ASSERT_EQ(1, counter->numWarnings);

  DWIO_WARN("test warning #2");
  ASSERT_EQ(2, counter->numExceptions);
  ASSERT_EQ(2, counter->numWarnings);

  ASSERT_ANY_THROW(DWIO_ENSURE_EQ(1, 2));
  ASSERT_EQ(3, counter->numExceptions);
  ASSERT_EQ(2, counter->numWarnings);

  // Verifier duplicate registration is rejected
  ASSERT_ANY_THROW(
      registerExceptionLogger(std::make_unique<TestExceptionLogger>(counter)));
}

TEST(LoggedExceptionTest, traceCollectionControlTest) {
  // Test exception controlling flags.
  for (const bool traceCollectionEnabled : {false, true}) {
    testTraceCollectionSwitchControl(traceCollectionEnabled);
  }
}
